﻿using UnityEngine;
using System.Collections;
using System;

// 飞行道具(挂到可飞行的技能效果上)
// 销毁不能简单的按照时间销毁 1
// 有目标性 1
// 追踪 1
public class FlyObject : MonoBehaviour
{
    public Creature Target;
    public float Speed = 2;
    public float Radius = 0.15f;

    // 打击到目标时，通知外界
    public Action<FlyObject, Creature> OnHitTargetCallback;

    private Rigidbody _rig;

    // Use this for initialization
    void Awake()
    {
        _rig = gameObject.AddComponent<Rigidbody>();
        _rig.useGravity = false;

        var collider = gameObject.AddComponent<SphereCollider>();
        collider.radius = Radius;
        collider.isTrigger = true;
    }

    private void Update()
    {
        _rig.velocity = (Target.transform.position - transform.position).normalized * Speed;
    }

    private void OnTriggerEnter(Collider other)
    {
        var target = other.GetComponent<Creature>();
        if (target == null)
        {
            return;
        }

        // 打击到了目标
        if (Target == target)
        {
            if (OnHitTargetCallback != null)
            {
                OnHitTargetCallback(this, target);
            }
            
        }
    }
}
